package com.zb.kc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Sets;
import com.zb.kc.commonutils.ResultCode;
import com.zb.kc.entity.EduChapter;
import com.zb.kc.dao.EduChapterDao;
import com.zb.kc.entity.EduVideo;
import com.zb.kc.entity.vo.ChapterVo;
import com.zb.kc.entity.vo.VideoVo;
import com.zb.kc.service.IEduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.kc.service.IEduVideoService;
import com.zb.kc.servicebase.exceptionhandler.KgcException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wanggen
 * @since 2020-04-10
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterDao, EduChapter> implements IEduChapterService {

    @Autowired
    private IEduVideoService videoService;

    @Autowired
    private EduChapterDao chapterDao;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        // 定义结合返回最终的结果
        List<ChapterVo> chapterVos = chapterDao.selectByCourseId(courseId);
        // 如果为空 直接返回
        if (ObjectUtil.isNull(chapterVos)) {
            return chapterVos;
        }
        // 根据课程id 查询所有的小节
        List<VideoVo> videoVos = videoService.selectByCourseId(courseId);
        if (ObjectUtil.isNull(videoVos)) {
            return chapterVos;
        }
        // 用来存放已经遍历过的小节id
        Set<String> videoVoIds = Sets.newHashSetWithExpectedSize(videoVos.size());
        chapterVos.forEach(e -> {
            List<VideoVo> chapterChildren = new LinkedList<>();
            videoVos.stream()
                    .filter(v -> !videoVoIds.contains(v.getId()))
                    .filter(v -> v.getChapterId().equals(e.getId()))
                    .forEach(v -> {
                        videoVoIds.add(v.getId());
                        chapterChildren.add(v);
                    });
            e.setChildren(chapterChildren);
        });
        // 给chatperVo的childen赋值
        return chapterVos;
    }

    /**
     * 删除章节，要先判断章节下是否有小节，如果有则禁止用户删除
     * @param chapterId
     */
    @Override
    public void deleteChapter(String chapterId) {
        int count = videoService.count(new QueryWrapper<EduVideo>().select("chapter_id").eq("chapter_id", chapterId));
        if (count > 0) {
            throw new KgcException(ResultCode.CANNOT_DELETE_CHAPTER);
        }
        baseMapper.deleteById(chapterId);
    }

    @Override
    public List<ChapterVo> nestedList(String courseId) {
        return null;
    }
}